package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.SkuSearchVo;
import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig;
import com.atguigu.gulimall.search.constant.SearchConstant;
import com.atguigu.gulimall.search.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProductServiceImpl implements ProductService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public boolean up(List<SkuSearchVo> skuSearchVos) throws IOException {


        BulkRequest bulkRequest = new BulkRequest(SearchConstant.PRODUCT_INDEX);
        for (SkuSearchVo skuSearchVo : skuSearchVos) {
            IndexRequest indexRequest = new IndexRequest();
            indexRequest.id(skuSearchVo.getSkuId()+"");
            indexRequest.source(JSON.toJSONString(skuSearchVo), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }

        BulkResponse response = restHighLevelClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
        boolean hasFailures = response.hasFailures();
        BulkItemResponse[] items = response.getItems();
        List<String> collect = Arrays.stream(items).map(item -> item.getId()).collect(Collectors.toList());
        log.info("商品上架成功，id集合:{}",collect);
        return hasFailures;
    }
}
